﻿using Fuse8.ContentManagementFramework.Administration.Models;
using Fuse8.DomainFramework.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Fuse8.ContentManagementFramework.Administration.Logic
{
    public abstract class BaseFileViewProvider<T> : IFileViewProvider<T>
    {
        #region Properties

        public virtual string PhisicalPath
        {
            get;
            protected set;
        }

        public virtual string CmsFileItemName
        {
            get
            {
                return "Not defined";
            }
        }

        public virtual string[] IgnorePath
        {
            get
            {
                return new string[] { ".svn" };
            }
        }

        #endregion Properties

        #region IFileViewProvider Members

        public CmsAdminFileItem GetRoot(int? id)
        {
            CmsAdminFileItem result = null;

            if (Directory.Exists(PhisicalPath))
            {
                result = new CmsAdminFileItem
                {
                    Name = CmsFileItemName,
                    IsFile = false,
                    RootDirectory = string.Empty,
                    NestedFileItems =
                        GetNested(new DirectoryInfo(PhisicalPath), string.Format("{0}/{1}", string.Empty, CmsFileItemName)).ToArray()
                };
            }

            return result;
        }

        #endregion IFileViewProvider Members

        #region Protected methods

        protected virtual IList<CmsAdminFileItem> GetNested(DirectoryInfo directoryInfo, string rootDirectory)
        {
            Guard.ArgumentNotNull(directoryInfo, "directoryInfo");

            List<CmsAdminFileItem> result = new List<CmsAdminFileItem>();

            result.AddRange(
                directoryInfo.GetDirectories().Where(p => !IgnorePath.Contains(p.Name)).Select(
                    p => new CmsAdminFileItem
                    {
                        Id = p.Name,
                        Name = p.Name,
                        RootDirectory = rootDirectory,
                        IsFile = false,
                        NestedFileItems = GetNested(p, string.Format("{0}/{1}", rootDirectory, p.Name)).ToArray()
                    })
                    .ToArray());

            result.AddRange(
                directoryInfo.GetFiles().Select(
                    p => new CmsAdminFileItem
                    {
                        Id = p.Name,
                        RootDirectory = rootDirectory,
                        Ext = p.Extension.ToLower().TrimStart(new char[] { '.' }),
                        Name = p.Name,
                        IsFile = true
                    })
                    .ToArray());

            return result.OrderBy(p => !p.IsFile).ToList();
        }

        #endregion Protected methods
    }
}